﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using SetSailCommon;
using SetSailControl;
using SetSailDal;
using SetSailModel;

namespace SetSailView
{
    /// <summary>
    /// 联运读档
    /// </summary>
    [ToolboxItem(false)]
    public partial class Frm_LYDD : UserControl
    {
        public Frm_LYDD()
        {
            InitializeComponent();
        }
        //我的文档欧卡车队联运存档
        string MyFilePath = Environment.GetFolderPath(Environment.SpecialFolder.Personal) + "\\Euro Truck Simulator 2\\profiles";
        string EST2Path = Environment.GetFolderPath(Environment.SpecialFolder.Personal) + "\\ETS2MP";
        string PathFileName = "";//获取存档文件名
        string SelectDDLX = "";//读档类型
        string SelectFXMS = "";//飞行模式
        List<Cookie_ZD> ls_filename = new List<Cookie_ZD>();

        private void Frm_LYDD_Load(object sender, EventArgs e)
        {
            try
            {
                //默认全套档
                PathFileName = CookieData.getInstance().ZDGL.Where(a => a.MXDM == "QTFILE").FirstOrDefault().MXZ;

                //读档类型数据源
                List<Cookie_ZD> ls = CookieData.getInstance().ZDGL.Where(a => a.ZDDM == "CDDLX").ToList();
                Dictionary<string, string> dic = new Dictionary<string, string>();
                foreach (var item in ls)
                {
                    dic.Add(item.MXZ, item.MXMC);
                }
                TxtDDLX.DataSource = dic;
                TxtDDLX.SelectItem = new List<string>() { "全套" };
                SelectDDLX = "全套";
                //飞行模式数据源
                TxtFXMS.DataSource = new Dictionary<string, string>() { { "0", "关闭" }, { "1", "打开" } };
                TxtFXMS.SelectItem = new List<string>() { "0" };
                SelectDDLX = "0";
                //联运公告
                var result = MainDal.Query_LYGG("联运");
                if (result.Code == ResultCode.Success && result.Data != null)
                {
                    TxtLYGG.Text = result.Data.GGNR;
                }
                else
                {
                    TxtLYGG.Text = "无";
                }

                //车队前缀名
                string cdqzm = CookieData.getInstance().ZDGL.Where(a => a.ZDDM == "CDQZM").FirstOrDefault().MXMC;
                TxtCDQZM.InputText = cdqzm;

                //问题反馈类型
                List<Cookie_ZD> ls_kflx = CookieData.getInstance().ZDGL.Where(a => a.ZDDM == "FKLX").ToList();
                List<KeyValuePair<string, string>> lscbm_kflx = new List<KeyValuePair<string, string>>();

                foreach (var item in ls_kflx)
                {
                    lscbm_kflx.Add(new KeyValuePair<string, string>(item.MXDM, item.MXMC));
                }
                TxtFKLX.Source = lscbm_kflx;
                TxtFKLX.SelectedValue = "bug";
            }
            catch (Exception ex)
            {
                MessShow.ShowMistake(ex.Message);
            }

        }

        /// <summary>
        /// 获取服务器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ucBtnExt1_BtnClick(object sender, EventArgs e)
        {
            bool flag = CommonHelper.GetPing();
            if (flag)
            {
                TxtGetIP.InputText = "43.***.***.99";
            }
            else
            {
                MessShow.ShowHint("无法链接到服务器");
            }
        }

        /// <summary>
        /// 读档类型change事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TxtDDLX_SelectedItemChanged(object sender, EventArgs e)
        {
            if (TxtDDLX.SelectItem.Count == 0)
            {
                if (SelectDDLX == "全套")
                    TxtDDLX.SelectItem = new List<string>() { "本体" };
                else
                    TxtDDLX.SelectItem = new List<string>() { "全套" };
            }
            else
                SelectDDLX = TxtDDLX.SelectItem[0].Trim();
        }

        /// <summary>
        /// 飞行模式change事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TxtFXMS_SelectedItemChanged(object sender, EventArgs e)
        {
            if (TxtFXMS.SelectItem.Count == 0)
            {
                if (SelectFXMS == "0")
                    TxtFXMS.SelectItem = new List<string>() { "1" };
                else
                    TxtFXMS.SelectItem = new List<string>() { "0" };
            }
            else
                SelectFXMS = TxtFXMS.SelectItem[0].Trim();
        }

        /// <summary>
        /// 获取存档
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ucBtnExt2_BtnClick(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(TxtGetIP.InputText.Trim()))
            {
                MessShow.ShowHint("请先获取服务器");
                return;
            }

            //验证文件夹是否存在
            if (!Directory.Exists(MyFilePath))
            {
                MessShow.ShowHint("请先安装游戏");
                return;
            }

            if (TxtDDLX.SelectItem[0].Trim() == "全套")
                PathFileName = CookieData.getInstance().ZDGL.Where(a => a.MXDM == "QTFILE").FirstOrDefault().MXZ;
            else
                PathFileName = CookieData.getInstance().ZDGL.Where(a => a.MXDM == "BTFILE").FirstOrDefault().MXZ;

            //判断今日是否有存档
            var result2 = LYDDDal.Query_FileExist(DateTime.Today.ToString("yyyy-MM-dd"), TxtDDLX.SelectItem[0].Trim());
            if (result2.Code == ResultCode.Fail)
            {
                MessShow.ShowHint(result2.Message);
                return;
            }
            else if (result2.Code == ResultCode.Exception)
            {
                MessShow.ShowMistake(result2.Message);
                return;
            }
            string cosPath = DateTime.Today.ToString("yyyy-MM-dd") + "/" + PathFileName + ".zip";
            //string cosPath = "2022-06-13" + "/" + PathFileName + ".zip";
            ControlHelper.ThreadRunExt(this, () =>
            {
                CosHelper helper = new CosHelper();
                helper.TransferDownloadObject(MyFilePath, PathFileName + ".zip", cosPath).Wait();

                ControlHelper.ThreadInvokerControl(this, () =>
                {
                    if (helper.result2 != "ok")
                    {
                        MessShow.ShowHint(helper.result2);
                    }
                    else
                    {
                        //获取压缩包大小
                        decimal size = 0;
                        string[] arr = Directory.GetFiles(MyFilePath);
                        foreach (var item in arr)
                        {
                            if (item.Contains(PathFileName + ".zip"))
                            {
                                FileInfo fi = new FileInfo(item);
                                size = Convert.ToDecimal(Convert.ToDecimal(fi.Length) / 1024 / 1024);
                                break;
                            }
                        }

                        QH_CDDJL cddjl = new QH_CDDJL();
                        cddjl.ID = CommonHelper.GetNewGuid();
                        cddjl.CZZH = CookieData.getInstance().YHXX.DLZH;
                        cddjl.SYLL = size;
                        cddjl.CDDLX = "读档";
                        var result = LYDDDal.Add_CDDJL(cddjl);
                        if (result.Code == ResultCode.Success)
                            MessShow.ShowSure("已获取存档，请同步存档");
                        else if (result.Code == ResultCode.Fail)
                            MessShow.ShowHint(result.Message);
                        else
                            MessShow.ShowMistake(result.Message);
                    }
                });
            }, null, this);
        }

        /// <summary>
        /// 同步存档
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ucBtnExt3_BtnClick(object sender, EventArgs e)
        {
            string PathFileName = "";
            if (TxtDDLX.SelectItem[0].Trim() == "全套")
                PathFileName = CookieData.getInstance().ZDGL.Where(a => a.MXDM == "QTFILE").FirstOrDefault().MXZ;
            else
                PathFileName = CookieData.getInstance().ZDGL.Where(a => a.MXDM == "BTFILE").FirstOrDefault().MXZ;

            string path = MyFilePath + "\\" + PathFileName + ".zip";

            //验证文件是否存在
            if (File.Exists(path))
            {
                string filename = MyFilePath + "\\" + PathFileName;
                //验证当前路径下是否存在save目录
                if (Directory.Exists(filename + "\\save"))
                {
                    string err = CommonHelper.DeleteDirectory(filename, "save");
                    if (!string.IsNullOrWhiteSpace(err))
                    {
                        MessShow.ShowHint(err);
                        return;
                    }
                }
                string error = "";
                bool flag = CommonHelper.UnZipFile(path, filename, out error);
                if (flag)
                {
                    // 2、根据路径字符串判断是文件还是文件夹
                    FileAttributes attr = File.GetAttributes(path);
                    // 3、根据具体类型进行删除
                    if (attr == FileAttributes.Directory)
                    {
                        // 3.1、删除文件夹
                        Directory.Delete(path, true);
                    }
                    else
                    {
                        // 3.2、删除文件
                        File.Delete(path);
                    }
                    MessShow.ShowSure("联运存档（" + TxtDDLX.SelectItem[0].Trim() + "）已同步成功");
                }
                else
                {
                    MessShow.ShowHint(error);
                }
            }
            else
            {
                MessShow.ShowHint("请先获取文档");
                return;
            }
        }

        /// <summary>
        /// 提交反馈
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ucBtnExt4_BtnClick(object sender, EventArgs e)
        {
            QH_WTFK wtfk = new QH_WTFK();
            wtfk.ID = CommonHelper.GetNewGuid();
            wtfk.FKZH = CookieData.getInstance().YHXX.DLZH;
            wtfk.FKLX = TxtFKLX.SelectedValue;
            wtfk.FKNR = TxtFKNR.Text;

            var result = LYDDDal.Add_KWFK(wtfk);
            if (result.Code == ResultCode.Success)
            {
                TxtFKLX.SelectedValue = "bug";
                TxtFKNR.Text = "";
                MessShow.ShowSure("已提交，感谢您的反馈");
            }
            else if (result.Code == ResultCode.Fail)
                MessShow.ShowHint(result.Message);
            else
                MessShow.ShowMistake(result.Message);
        }

        /// <summary>
        /// 保存飞行模式设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ucBtnExt5_BtnClick(object sender, EventArgs e)
        {
            if (TxtFXMS.SelectItem.Count == 0)
            {
                MessShow.ShowHint("请选择关闭/打开飞行设置");
                return;
            }
            try
            {
                string isChecked = TxtFXMS.SelectItem[0].Trim();
                string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal) + "\\Euro Truck Simulator 2\\config.cfg";
                //修改飞行模式存档
                string[] read = File.ReadAllLines(path);
                if (isChecked == "1")
                {
                    int nums = 0;
                    int end = 0;
                    foreach (var item in read)
                    {
                        //if (nums == 159)
                        //{

                        //}
                        if (item == "uset g_console \"0\"")
                        {
                            read[nums] = item.Replace("uset g_console \"0\"", "uset g_console \"1\"");
                            end++;
                        }
                        if (item == "uset g_developer \"0\"")
                        {
                            read[nums] = item.Replace("uset g_developer \"0\"", "uset g_developer \"1\"");
                            end++;
                        }
                        if (end > 1) break;
                        nums++;
                    }
                }
                else
                {
                    int nums = 0;
                    int end = 0;
                    foreach (var item in read)
                    {
                        //if (nums == 159)
                        //{

                        //}
                        if (item == "uset g_console \"1\"")
                        {
                            read[nums] = item.Replace("uset g_console \"1\"", "uset g_console \"0\"");
                            end++;
                        }
                        if (item == "uset g_developer \"1\"")
                        {
                            read[nums] = item.Replace("uset g_developer \"1\"", "uset g_developer \"0\"");
                            end++;
                        }
                        if (end > 1) break;
                        nums++;
                    }
                }
                StringBuilder sb = new StringBuilder();
                foreach (var item in read)
                {
                    sb.Append(item + "\n");
                }
                File.WriteAllText(path, sb.ToString());
                MessShow.ShowSure("设置成功，请重新登录游戏");
            }
            catch (Exception ex)
            {
                MessShow.ShowMistake(ex.Message);
            }


        }

        /// <summary>
        /// 复制前缀名
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ucBtnExt7_BtnClick(object sender, EventArgs e)
        {
            Clipboard.Clear();//清空粘贴板信息
            Clipboard.SetData(DataFormats.Text, TxtCDQZM.InputText.Trim());//往系统粘贴板设置数据
            MessShow.ShowSure("已复制前缀名到剪贴板");
        }

        /// <summary>
        /// 同步前缀名
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ucBtnExt6_BtnClick(object sender, EventArgs e)
        {
            MessShow.ShowSure("该功能正在维护");
            return;
            if (!Directory.Exists(EST2Path))
            {
                MessShow.ShowHint("未查找到联机插件路径");
                return;
            }
            try
            {
                string path = Environment.CurrentDirectory + "\\config.dat";
                File.Copy(path, EST2Path + "\\config.dat", true);
                MessShow.ShowSure("已同步前缀名");
            }
            catch (Exception ex)
            {
                MessShow.ShowMistake(ex.Message);
            }

        }

        /// <summary>
        /// 检测是否已同步前缀名
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer2_Tick(object sender, EventArgs e)
        {
            //查看是否有同步前缀名
            string filelen = CookieData.getInstance().ZDGL.Where(a => a.MXDM == "CDQZMLENGTH").FirstOrDefault().MXZ;
            string path = EST2Path + "\\config.dat";
            if (!Directory.Exists(EST2Path))
            {
                timer2.Enabled = false;
                MessShow.ShowHint("未查找到TMP插件路径");
                return;
            }
            if (!File.Exists(path) || new FileInfo(path).Length != Convert.ToInt32(filelen))
            {
                timer2.Enabled = false;
                DialogResult res = MessShow.ShowQuery("前缀名未同步，是否同步？");

                if (res == DialogResult.OK)
                {
                    ucBtnExt6_BtnClick(null, null);
                }
            }
        }
    }
}